"""2024.3.0 Ajout des options des plan de paiement

Revision ID: 947d347d3038
Revises: 1b5ae0fd7e16
Create Date: 2024-03-20 18:02:13.959416

"""

# revision identifiers, used by Alembic.
revision = "947d347d3038"
down_revision = "1b5ae0fd7e16"

from alembic import op
import sqlalchemy as sa
from caerp.alembic.utils import column_exists
from caerp.models.project.business import BusinessPaymentDeadline
from caerp.compute import math_utils


def update_database_structure():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column(
        "business_payment_deadline", sa.Column("order", sa.Integer(), nullable=True)
    )
    op.add_column(
        "business_payment_deadline", sa.Column("description", sa.Text(), nullable=True)
    )
    op.add_column("business_payment_deadline", sa.Column("amount_ttc", sa.BigInteger()))
    op.add_column("business_payment_deadline", sa.Column("amount_ht", sa.BigInteger()))
    op.add_column(
        "business_payment_deadline", sa.Column("date", sa.Date(), nullable=True)
    )
    # ### end Alembic commands ###


def migrate_datas():
    from alembic.context import get_bind
    from zope.sqlalchemy import mark_changed
    from caerp_base.models.base import DBSESSION

    session = DBSESSION()
    conn = get_bind()
    sql_query = sa.select(BusinessPaymentDeadline).where(
        BusinessPaymentDeadline.deposit == False
    )

    for deadline in session.execute(sql_query).scalars():
        if deadline.payment_line:
            deadline.order = deadline.payment_line.order
            deadline.description = deadline.payment_line.description
            deadline.amount_ttc = deadline.payment_line.amount
            deadline.amount_ht = deadline.amount_ttc
            if deadline.estimation:
                total = deadline.estimation.total()
                if total != 0:
                    ratio = math_utils.percent(
                        deadline.amount_ttc, total, default=0, precision=5
                    )
                    if len(deadline.estimation.get_tvas().keys()) == 1:
                        deadline.amount_ht = math_utils.percentage(
                            deadline.estimation.ht, ratio
                        )
                    else:
                        deadline.amount_ht = 0
                        for tva, ht in deadline.estimation.tva_ht_parts().items():
                            deadline.amount_ht += math_utils.percentage(ht, ratio)
            if deadline.estimation.paymentDisplay != "ALL_NO_DATE":
                deadline.date = deadline.payment_line.date
            session.merge(deadline)
            session.flush()

    sql_query = sa.select(BusinessPaymentDeadline).where(
        BusinessPaymentDeadline.deposit == True
    )

    for deadline in session.execute(sql_query).scalars():
        deadline.order = 0
        deadline.description = f"Facture d'acompte {deadline.estimation.deposit}%"
        deadline.amount_ttc = deadline.estimation.deposit_amount_ttc()
        deadline.amount_ht = deadline.estimation.deposit_amount_ht()
        session.merge(deadline)
        session.flush()

    mark_changed(session)
    session.flush()


def upgrade():
    update_database_structure()
    migrate_datas()


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    for table, column in (
        ("business_payment_deadline", "date"),
        ("business_payment_deadline", "amount"),
        ("business_payment_deadline", "description"),
        ("business_payment_deadline", "order"),
    ):
        if column_exists(table, column):
            op.drop_column(table, column)
